﻿#nullable disable
using Furion.DependencyInjection;
using IMES.BLL.Dtos;
using IMES.Entity;
using Mapster;

namespace IMES.BLL
{
    /// <summary>
    /// 用户仓储处理
    /// </summary>
    public class UserRep : BaseRepository<User>, ITransient
    {
        public List<UserDto> AllUserList()
        {
            List<UserDto>? result = Context.Queryable<User>()
                .Where(u=>!u.IsDeleted)
                .Select(u=>new UserDto()
                {
                    Id = u.Id,
                    LoginIP = u.LoginIP,
                    LoginTime = u.LoginTime,
                    Mobile = u.Mobile,
                    Remark = u.Remark,
                    Usable = u.Usable,
                    UserCode = u.UserCode,
                    UserName = u.UserName,
                    CreateTime=u.CreateTime,
                    Creator=u.Creator,
                }).ToList();

            if (result != null && result.Count > 0)
            {
                var roles = Context.Queryable<Role>()
                .InnerJoin<RoleUser>((r, ru) => r.Id.Equals(ru.RoleID))
                .Select((r, ru) => new UserRoleDto()
                {
                    Id = ru.Id,
                    RoleID = ru.RoleID,
                    RoleName = r.Name,
                    UserID = ru.UserID,
                }).ToList();

                foreach (UserDto userDto in result)
                {
                    LoadUserRoleData(userDto, roles);
                }
            }
            return result;
        }

        private void LoadUserRoleData(UserDto user,List<UserRoleDto> userRoles)
        {
            if(userRoles!=null && userRoles.Count>0)
            {
                string[] userRoleNames =userRoles.Where(u => u.UserID.Equals(user.Id)).Select(u=>u.RoleName).ToArray();
                if(userRoleNames != null && userRoleNames.Length > 0)
                {
                    user.RoleName =String.Join(",", userRoleNames);
                }
            }
        }

        /// <summary>
        /// 登录校验
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns> 当前用户Id</returns>
        public UserVO LoginCheck(string userName,string password)
        { 
            var userInfo = Context.Queryable<User>().Where(a => a.UserCode.Equals(userName)).First();
            if(userInfo != null && userInfo.Password.Equals(password) && userInfo.Id>0) {
                return userInfo.Adapt<UserVO>();
            }
            return null;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <exception cref="NotImplementedException"></exception>
        public void DeleteUser(long userId)
        {
            try
            {
                Context.Deleteable<RoleUser>(ru=>ru.UserID.Equals(userId)).ExecuteCommand();
                Context.Deleteable<User>(u=>u.Id.Equals(userId)).ExecuteCommand();
            }
            catch (Exception ex)
            {
                throw new Exception("删除失败:" + ex.Message);
            }
        }

        /// <summary>
        /// 获取用户信息详情
        /// </summary>
        /// <param name="pk"></param>
        /// <returns></returns>
        public User GetUserDtl(long pk)
        {
            User user = base.GetById(pk);
            var roles =Context.Queryable<RoleUser>()
                .InnerJoin<Role>((ru,rl)=>ru.RoleID.Equals(rl.Id))
                .Where((ru,rl)=>ru.UserID.Equals(pk))
                .Select((ru,rl)=>rl).ToList();
            user.Roles = roles;
            return user;
        }
        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user"></param>
        /// <param name="roles"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void AddUser(User user, List<long> roles)
        {
            base.AddAsync(user);
            if(roles!=null && roles.Count>0)
            {
                List<RoleUser> users = new List<RoleUser>();
                foreach (long item in roles)
                {
                    users.Add(new RoleUser() { RoleID = item, UserID = user.Id });
                }
                Context.Insertable<RoleUser>(users).ExecuteCommand();
            }
        }
        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="user"></param>
        /// <param name="roles"></param>
        public void UpdateUser(User user, List<long> roles)
        {
            base.UpdateAsync(user);
            if(roles!=null && roles.Count>0)
            {
                Context.Deleteable<RoleUser>().Where(ru => ru.UserID.Equals(user.Id)).ExecuteCommand();
                List<RoleUser> users = new List<RoleUser>();
                foreach (long item in roles)
                {
                    users.Add(new RoleUser() { RoleID = item, UserID = user.Id });
                }
                Context.Insertable<RoleUser>(users).ExecuteCommand();
            }
        }
    }
}
